<template>
  <a-row type="flex" style="flex-flow: inherit;" v-if="reloading">
    <a-col :flex="toggle?'260px':'30px'" style="margin-right: 12px;background-color: #fff;">
      <depart-tree :rootOpened="true" :multi="false" @ok="getTreeData" @toggleBool="toggleBool" />
    </a-col>
    <a-col flex="auto" style="width: 0;">
      <a-card :bordered="false" style="margin-bottom: 10px">
        <!-- 查询区域 -->
        <div class="table-page-search-wrapper">
          <a-form-model layout="inline" ref="ruleForm" :model="queryParam">
            <z-form-item
              :datas="fieldArr"
              :form="queryParam"
              :submitAction="{show: true, toggle: true, span: 8}"
              @change="getChangeTime"
              @onSubmit="onQuery"
              @onReset="onResetForm"
            />
          </a-form-model>
        </div>
      </a-card>
      <a-card :bordered="false">
        <!-- 操作按钮区域 -->
        <div class="table-operator">
          <div>
            <a-button type="primary" @click="clickPush()" v-if="$routeType===2">新增</a-button>
            <a-button v-if="$routeType===2" @click="handleImportXls">导入</a-button>
            <a-button @click="handleExport">导出</a-button>
          </div>
        </div>
        <!-- 表格展示 -->
        <div class="table-page-content">
          <z-table
            ref="table"
            rowKey="id"
            :showAlert="false"
            :showSelection="true"
            :loading="loading"
            :columns="columns"
            :dataSource="pageData"
            @selectedRow="onSelectedRow"
            @change="onTableChange"
          />
        </div>
        <!--弹窗区域-->
        <handle-modal ref="handleModalRef" @ok="modalFormOk" />
        <j-import-modal ref="importModal" :url="getImportUrl()" @ok="importOk">
          <a-button type="link" style="position: absolute;left: 20px;" @click="dowloadsXls"> 下载数据模板 </a-button>
        </j-import-modal>
      </a-card>
    </a-col>
  </a-row>
</template>

<script>
import * as personServiceApi from '@/api/sjsk/personService'
import departTree from '../../modules/departTree'
import handleModal from '../../modules/handleModal'
import { downLoadFileReader } from '@/utils/export-util/util'

export default {
  components: { departTree, handleModal },
  data() {
    return {
      loading: false,
      toggle: true,
      reloading: true,
      selectKeys: [],
      queryParam: {},
      fieldArr: [
        {label: '吸毒人员姓名', prop: 'name', tagType: 'input', span: 8},
        {label: '吸毒人员身份证', prop: 'identityCard', tagType: 'input', span: 8},
        {label: '人员类型', prop: 'personType', tagType: 'dict-select', dictCode:'social_person_type', span: 8, toggle: false},
        {label: '入库时间', prop: 'date', tagType: 'range-picker', format: 'YYYY-MM-DD', span: 8, toggle: false},
        {label: '性别', prop: 'sex', tagType: 'dict-select', dictCode:'sex',span: 8, toggle: false},
      ],
      columns: [
        {
          title: '姓名',
          dataIndex: 'realName',
          width: 80,
          align: 'center',
          customRender: text => {
            return <j-ellipsis value={text} length={14} />
          }
        },
        {
          title: '个案编号',
          dataIndex: 'caseNo',
          width: 80,
          align: 'center',
          customRender: text => {
            return text?<j-ellipsis value={text} length={14} />: '--'
          }
        },
        {
          title: '性别',
          dataIndex: 'sex',
          width: 60,
          align: 'center',
          customRender: text => {
            return <j-ellipsis value={this.$filterDictTextByCache('sex', text)} length={14} />
          }
        },
        {
          title: '身份证号',
          dataIndex: 'identityCard',
          width: 130,
          align: 'left',
          customRender: text => {
            return <j-ellipsis value={text} length={18} />
          }
        },
        {
          title: '人员类型',
          dataIndex: 'personType',
          width: 80,
          align: 'center',
          customRender: text => {
            return <j-ellipsis value={this.$filterDictTextByCache('social_person_type', text)} length={14} />
          }
        },
        {
          title: '联系电话',
          dataIndex: 'phone',
          width: 100,
          align: 'center',
          customRender: text => {
            return text?<j-ellipsis value={text} length={14} />: '--'
          }
        },
        {
          title: '管辖地区',
          dataIndex: 'householdTown',
          width: 80,
          align: 'center',
          customRender: text => {
            return text?<j-ellipsis value={text} length={8} />: '--'
          }
        },
        {
          title: '入库时间',
          dataIndex: 'createTime',
          width: 100,
          align: 'center'
        },
        {
          title: '操作',
          width: 120,
          align: 'center',
          dataIndex: 'action',
          customRender: (text, record, index) => {
            return (
              <a-space size={6}>
                {this.$routeType===2 ?
                  <a-button type="link" style={'padding:0'} onClick={event => this.clickPush(record)}>编辑</a-button> : null
                }
                {record.belongManagerId ?
                  <a-button type="link" style={'padding:0'} onClick={event => this.handleConfirm('remove-distribution', record)}>解除分配</a-button>
                : <a-badge dot>
                    <a-button type="link" style={'padding:0'} onClick={event => this.handleModal('personnel-assignment', record)}>人员分配</a-button>
                  </a-badge>
                }
                {this.$routeType===1 ?
                  <a-button type="link" style={'padding:0'} onClick={event => this.handleModal('apply-remote-control', record)}> 申请异地管控 </a-button> : null
                }
              </a-space>
            )
          }
        }
      ],
      pageFilter: {
        pageNo: 1,
        pageSize: 10
      },
      pageData: {}
    }
  },
  computed: {
    $routeType() {
      let type = 1
      // 社会面有吸毒史人员列表
      if (this.$route.path==='/drugUsers/list') {
        type = 1
      // 社会面有吸毒史人员接案
      } else if(this.$route.path==='/drugUsers/connection-list'){
        type = 2
      }
      return type
    }
  },
  watch: {
    '$routeType': {
      immediate: true,
      deep: true,
      handler(val) {
        this.reload()
        this.onResetForm()
        // 表格
        let columnsIndex = this.columns.findIndex(item=> item.dataIndex ==='householdTown')
        let columns1 = {title: '是否结案', dataIndex: 'isCloseCase', width: 90, align: 'center', customRender: text => <j-ellipsis value={this.$filterDictTextByCache('dict_yn', text)} length={14}/> }
        let columns2 = {title: '结案类型', dataIndex: 'closeCaseType', width: 110, align: 'center', customRender: text => <j-ellipsis value={this.$filterDictTextByCache('closing_type', text)} length={14}/>}
        let columnsDataIndex = this.columns.findIndex(item=> item.dataIndex ===columns1.dataIndex)
        // 筛选搜索
        let fieldArrIndex = this.fieldArr.findIndex(item=> item.prop ==='sex')
        let field1 = { label: '标签筛选', prop: 'labelType', tagType: 'dict-select', dictOptions: [ { text: '请选择', value: '' }, { text: '异地管控人员', value: '1' }, ], span: 8, toggle: false }
        let field2 = { label: '是否结案', prop: 'isCloseCase', tagType: 'dict-select', dictCode:'dict_yn', span: 8, toggle: false }
        let field3 = { label: '结案类型', prop: 'closeCaseType', tagType: 'dict-select', dictCode:'closing_type', span: 8, toggle: false }
        let fieldArrProp = this.fieldArr.findIndex(item=> item.prop ===field1.prop)
        if (val===1) {
          if(columnsDataIndex<0) {
            this.columns.splice(columnsIndex+1, 0, columns1, columns2)
          }
          if(fieldArrProp<0) {
            this.fieldArr.splice(fieldArrIndex+1, 0, field1, field2, field3)
          }
        } else {
          if(columnsDataIndex>0) {
            this.columns.splice(columnsIndex+1, 2)
          }
          if(fieldArrProp>0) {
            this.fieldArr.splice(fieldArrIndex+1, 3)
          }
        }
      }
    },
    // 组织机构树-联动筛选人员列表
    'queryParam.departmentId'(newVal, oldVal){
      this.modalFormOk()
    }
  },
  // created() {},
  // mounted() {
  //   this.onQuery()
  // },
  methods: {
    onQuery() {
      this.pageFilter.pageNo = 1
      this.refreshTable()
    },
    onResetForm() {
      const queryParam = (({ departmentId })=>({ departmentId }))(this.queryParam) //清空对象，只保留departmentId元素
      this.queryParam = queryParam
      this.pageFilter.pageNo = 1
      this.pageFilter.pageSize = 10
      this.refreshTable()
    },
    onSelectedRow(keys) {
      this.selectKeys = keys
      this.isDisabled = keys.length > 0 ? false : true
    },
    onTableChange(pagination, pageFilter, sorter) {
      this.pageFilter = Object.assign({}, this.pageFilter, pagination)
      this.refreshTable()
    },
    refreshTable() {
      this.$set( this.queryParam, 'isSubmit', this.$routeType===1?1: 2 ) //是否提交 1：是（社会面案主人员列表） 2：否（社会面接案人员列表）
      let {date, ...dataParam} = this.queryParam // 剔除date元素，dataParam最新的对象
      
      let queryParam = Object.assign({}, dataParam, this.pageFilter)
      // delete queryParam.isSubmit
      this.loading = true
      personServiceApi
        .getSocialPersonList(queryParam)
        .then(res => {
          this.loading = false
          if (res.success) {
            this.pageData = res.result ? res.result : {}
            this.$refs.table.onClearRowKeys()
          } else {
            this.$message.warn(res.message?res.message: '请求失败！')
          }
        })
        .catch(e => {
          this.loading = false
          this.$message.warn('请求失败！')
        })
    },
    // 确认框操作
    handleConfirm(key, record) {
      let that = this
      let title = key === 'remove-distribution'? '人员解除分配': ''
      let content = null
      this.$confirm({
        title: `确定${title}?`,
        content: h => content,
        onOk() {
          personServiceApi.socialRemoveDistribution(record.id).then((res) => {
            if (res.success) {
              that.$message.success(res.message?res.message:'操作成功')
              that.onQuery()
            } else {
              that.$message.warn(res.message?res.message:'操作失败')
            }
          }).catch(e=>{
            that.$message.warn("操作失败！")
          })
        },
        onCancel() {
          console.log('Cancel')
        },
        class: 'confirm',
      })
    },
    handleImportXls(){
      this.$refs.importModal.show()
    },
    getImportUrl(){
      return personServiceApi.socialPersonImportUrl
    },
    importOk(){
      this.onQuery()
    },
    // 导出
    handleExport(record) {
      let that = this
      let selectList = this.$refs.table.getSelectedRows()
      let idList1 = selectList.map(v => v.id).filter(obj => obj !== null && obj !== undefined && obj !== '')
      let idList2 = record && Object.keys(record).length > 0 && record.id ? [record.id] : []
      let params = Object.assign(
        {},
        {
          idList: selectList.length > 0 ? idList1 : idList2,
          querySocialPersonVO: this.queryParam
        }
      )
      this.$confirm({
        title: `是否确认导出？`,
        okText: '确定',
        onOk() {
          personServiceApi.socialPersonExport(params).then(async res => {
            const fileName = '社会面有吸毒史人员列表数据.xlsx'
            await downLoadFileReader(res, fileName)
            that.$refs.table.onClearRowKeys()
          })
        }
      })
    },
    // 弹窗成功接收
    modalFormOk() {
      this.onQuery()
    },
    // 弹窗操作
    handleModal(key, record) {
      if(key==='personnel-assignment') {
        // 区分社会面人员分配
        this.$set( record, 'controlPersonType', 2 )
      }
      if(key==='apply-remote-control') {
        // 区分社会面申请异地管控
        this.$set( record, 'controlPersonType', 2 )
      }
      this.$refs.handleModalRef.show(key, record, this.queryParam.departmentId)
      // this.$refs.handleModalRef.type = type
      // this.$refs.handleModalRef.disableSubmit = false
    },
    // 新增、编辑
    clickPush(record) {
      let id = record instanceof Object?record.id: record
      let path = id?`/drugUsers/connection-edit/${id}`:`/drugUsers/connection-add`
      this.$router.push({
        path: path,
        query: {},
      })
    },
    dowloadsXls() {
      // dataApi.getTemplate({type: 5}).then(res => {
      //   if (res.success) {
          const url = '/xlsx/社会面有吸毒史人员导入模板.xlsx'
          const elt = document.createElement('a')
          elt.setAttribute('href', url)
          elt.style.display = 'none'
          document.body.appendChild(elt)
          elt.click();
          document.body.removeChild(elt)
      //   } else {
      //     this.$message.warn('模板下载失败！')
      //   }
      // })
      // .catch(e => {
      //   this.$message.warn('请求失败！')
      // })
    },
    /** 重新加载组件 */
    reload() {
      this.reloading = false
      this.$nextTick(() => (this.reloading = true))
    },
    getTreeData(datas, id) {
      console.log(datas, id)
      console.log(id)
      this.$set( this.queryParam, 'departmentId', id )
    },
    toggleBool(bool) {
      console.log(bool)
      this.toggle = bool
    },
    // 获取组件的时间， prop为对应的字段，date为选中的时间值
    getChangeTime(prop, date) {
      if(prop === 'date') {
        this.$set( this.queryParam, 'startDate', date[0] )
        this.$set( this.queryParam, 'endDate', date[1] )
      }
    }
  }
}
</script>
<style lang="less" scoped>
@import '~@assets/less/common.less';
</style>
